<template>
  <div id="app">
    <transition :name="transitionName">
      <keep-alive>
        <router-view class="router" v-if="$route.meta.keepAlive"></router-view>
      </keep-alive>
    </transition>
    <transition :name="transitionName">
      <router-view class="router" v-if="!$route.meta.keepAlive"></router-view>
    </transition>
    <div v-if="hasBack" @click="$router.go(-1)" class="back-btn">
      <img src="@/assets/back.png" alt />
    </div>
  </div>
</template>
<script>
import { getAppInfo, getUserInfo, getInviteCode } from "@/api/profile";
import { mapMutations, mapState, mapActions } from "vuex";
import wx from "weixin-js-sdk";
import { getWXSDK } from "@/api/wx";
export default {
  data() {
    return {
      transitionName: "slide-right",
      hasBack: false
    };
  },
  watch: {
    $route: function(val) {
      this.hasBack = val.meta.hasBack === false ? false : true;
      if (this.$route.query.device == "fullscreen") {
        this.setFullscreen(1);
      }
      if (this.$route.path === "/" && this.menu.length) {
        this.$router.replace(this.menu[0].link);
      }
      if (this.isMiniProgram) {
        let postData = {
          url:
            window.location.href.split("#")[0] +
            "static/redirect.html?app3Redirect=" +
            encodeURIComponent(
              window.location.href.split("#")[0] +
                "#" +
                window.location.href.split("#")[1].split("?")[0]
            ),
          title: "康丽莱服务平台"
        };
        wx.miniProgram.postMessage({ data: JSON.stringify(postData) });
      }
    }
  },
  computed: {
    ...mapState({
      menu: state => state.app.menu,
      entryUrl: state => state.app.entryUrl,
      logo: state => state.app.logo,
      level: state => state.user.level,
      isFullscreen: state => state.app.isFullscreen
    })
  },
  methods: {
    ...mapMutations([
      "setAppInfo",
      "setEntryUrl",
      "setMiniProgram",
      "setFullscreen"
    ]),
    ...mapActions(["setUserInfo"]),
    onShare(invite_code) {
      let _this = this;
      let title = "视频商城服务平台";
      let desc = "欢迎来到视频商城服务平台";
      let imgUrl = this.logo;
      let link =
        window.location.href.split("#")[0] +
        "static/redirect.html?app3Redirect=" +
        encodeURIComponent(window.location.href.split("#")[0]) + `&invite_code=${invite_code}`;
      wx.onMenuShareAppMessage({
        title, // 分享标题
        desc, // 分享描述
        link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl, // 分享图标
        type: "link", // 分享类型,music、video或link，不填默认为link
        dataUrl: "", // 如果type是music或video，则要提供数据链接，默认为空
        success: res => {
          _this.arrowMask = false;
          this.$dialog.toast({
            mes: "分享成功",
            timeout: 1500,
            icon: "success"
          }); // 用户确认分享后执行的回调函数
          // console.log("分享给朋友成功返回的信息为:", res);
        },
        cancel: function(res) {
          _this.arrowMask = false;
          // 用户取消分享后执行的回调函数
          // console.log("取消分享给朋友返回的信息为:", res);
        }
      });

      //分享到朋友圈
      wx.onMenuShareTimeline({
        title, // 分享标题
        link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl, // 分享图标
        success: function(res) {
          _this.arrowMask = false;
          // 用户确认分享后执行的回调函数
          // console.log("分享到朋友圈成功返回的信息为:", res);
        },
        cancel: function(res) {
          _this.arrowMask = false;
          // 用户取消分享后执行的回调函数
          // console.log("取消分享到朋友圈返回的信息为:", res);
        }
      });
    }
  },
  beforeRouteLeave(to, from, next) {
    console.log(to.path);
    console.log(from.path);
    next();
  },
  created() {
    wx.miniProgram.getEnv(res => {
      // alert(res.miniprogram);
      if (res.miniprogram) {
        this.setMiniProgram(true);
      } else {
        this.setMiniProgram(false);
      }
    });
    //记录入口url
    if (typeof this.entryUrl === "undefined" || this.entryUrl === "") {
      this.setEntryUrl(location.href.split("#")[0]);
    }
    let signLink = /(Android)/i.test(navigator.userAgent)
      ? location.href.split("#")[0]
      : this.entryUrl;
    getInviteCode()
      .then(res => {
        if (res.data.datacode == 200) {
          return Promise.resolve(res.data.data.invite_code);
        }
      })
      .then(invite_code => {
        getWXSDK({ shareurl: signLink }).then(res => {
          if (res.status === 200) {
            // console.log(res.data.data);
            let data = res.data.data;
            wx.config({
              debug: false,
              appId: data.appId, // 和获取Ticke的必须一样------必填，公众号的唯一标识
              timestamp: data.timestamp, // 必填，生成签名的时间戳
              nonceStr: data.nonceStr, // 必填，生成签名的随机串
              signature: data.signature, // 必填，签名，见附录1
              jsApiList: ["onMenuShareAppMessage", "onMenuShareTimeline"]
            });
            //处理验证失败的信息
            wx.error(function(res) {
              // console.log("验证失败返回的信息:", res);
            });
            //处理验证成功的信息
            wx.ready(() => {
              // console.log("验证完成");
              this.onShare(invite_code);
            });
          }
        });
      });

    getAppInfo().then(res => {
      if (res.status === 200) {
        this.setAppInfo(res.data.data)
        this.$router.replace(this.menu[0].link);
        if (window.location.hash.indexOf("#/vip-invite") !== -1) {
          return;
        }

        if (this.$route.path === "/") {
          this.$router.replace(this.menu[0].link);
        }
      }
    });
    getUserInfo().then(res => {
      if (res.status === 200) {
        this.setUserInfo(res.data.data);
      }
    });
  }
};
</script>

<style lang="less">
html {
  background: #000;
  font-size: 50px;
}
.router {
  transition: all 0.15s ease;
}
.slide-left-enter,
.slide-right-leave-active {
  opacity: 0;
  // transform: translate3d(-100%, 0, 0);
}

.slide-left-leave-active,
.slide-right-enter {
  opacity: 1;
  // transform: translate3d(100%, 0, 0);
}
.back-btn {
  position: fixed;
  bottom: 4rem;
  right: 1rem;
  width: 1.4rem;
  height: 1.4rem;
  img {
    object-fit: cover;
    height: 100%;
    width: 100%;
  }
}
</style>
